package com.sakura.probe.service.impl;

import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sakura.probe.mapper.TopicImgMapper;
import com.sakura.probe.mapper.TopicMapper;
import com.sakura.probe.nosql.redis.RedisKey;
import com.sakura.probe.nosql.redis.RedisService;
import com.sakura.probe.pojo.Topic;
import com.sakura.probe.pojo.TopicImg;
import com.sakura.probe.service.HeadLineService;
import com.sakura.probe.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HeadLineServiceImpl implements HeadLineService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private TopicImgMapper topicImgMapper;

    @Autowired
    private TopicMapper topicMapper;


    @Override
    public List<Topic> getHeadLineList() {
        List<Topic> list = null;
        ObjectMapper mapper = new ObjectMapper();
        if (redisService.exist(RedisKey.getHeadLine())){
            //说明redis中存储了该数据,直接从redis中读取
            String HeadLineStr = redisService.get(RedisKey.getHeadLine());
            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class,Topic.class);
            //将相关key对应的value里的string转换成对象的实体类集合
            try {
                list = mapper.readValue(HeadLineStr,javaType);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }else {
            //从mysql中读取,读取后将数据存储在redis中
            Topic condition = new Topic();
            condition.setEnableStatus(1).setEnableHeadline(1);
            list = topicMapper.queryTopicList(condition,0,5);

            Topic temp = null;
            List<TopicImg> imgList = null;
            for (int i=0;i<list.size();i++) {
                temp = list.get(i);
                imgList = topicImgMapper.selectList(new QueryWrapper<TopicImg>().eq("topic_id", temp.getTopicId()));
                temp.setTopicImgList(imgList);
                list.set(i, temp);
            }
            String jsonString = null;
            try {
                jsonString = mapper.writeValueAsString(list);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            redisService.set(RedisKey.getHeadLine(),jsonString);
        }
        return list;
    }


}
